Skip to main content

104. Maximum Depth of Binary Tree

Question

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Example 1:

PascalTriangleAnimated

Input: root = [3,9,20,null,null,15,7]
Output: 3

Example 2:

Input: root = [1,null,2]
Output: 2

Constraints:

The number of nodes in the tree is in the range [0, 104].
-100 <= Node.val <= 100

Approach

  1. Starting from the root, recursively travel to the leaf node and return 0 because that means its on the 0th level.
  2. On every level, check the depth of left and right node respectively.
  3. Returns the larger depth + 1 (since the level starts from 0, but we need the number of levels which is > 0)

Solution

Go

/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func maxDepth(root *TreeNode) int {
if root == nil{
return 0
}else{
lDepth := maxDepth(root.Left)
rDepth := maxDepth(root.Right)

if lDepth > rDepth{
return lDepth + 1
}
return rDepth + 1
}
}

C++

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL) return 0;
else {
int lDepth = maxDepth(root->left);
int rDepth = maxDepth(root->right);

if (lDepth > rDepth) return lDepth+1;
return rDepth + 1;
}
}
};